package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class searchController {

    @Autowired
    private SearchService searchService;

    @GetMapping("/list")
    private String search(@RequestParam Map<String,String> searchMap, Model model)throws Exception{
        this.handlerSearchMap(searchMap);

        Map resultMap = searchService.search(searchMap);
        model.addAttribute("resultMap",resultMap);
        model.addAttribute("searchMap",searchMap);

        //封装分页信息
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.parseLong(String.valueOf(resultMap.get("total"))),//总记录数
                Integer.parseInt(String.valueOf(resultMap.get("pageNum"))),//当前页
                Page.pageSize   //每页显示条数
        );
        model.addAttribute("page",page);

        //拼装Url
        StringBuilder url = new StringBuilder("/search/list");
        if (searchMap!=null&&searchMap.size()>0){
            //有搜索条件
            url.append("?");
            for (String paramKey : searchMap.keySet()) {
                if (!"sortRule".equals(paramKey)&&!"sortField".equals(paramKey)&&!"pageNum".equals(paramKey)){
                    url.append(paramKey).append("=").append(searchMap.get(paramKey)).append('&');
                }
            }
            String urlString = url.toString();
            //去除路径上最后一个&
            urlString = urlString.substring(0, urlString.length() - 1);
            model.addAttribute("url",urlString);
        }else {
            model.addAttribute("url",url);
        }


        return "search";
    }

    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String,String> searchMap) throws Exception {
        //处理转码乱码问题
        this.handlerSearchMap(searchMap);

        Map resultMap = searchService.search(searchMap);
        return resultMap;
    }

    private void handlerSearchMap(Map<String, String> searchMap) {
        Set<Map.Entry<String, String>> entries = searchMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if (entry.getKey().startsWith("spec_")){
                searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
            }
        }
    }
}
